#!/bin/bash

if [[ $# -ne 2 ]]; then
	echo "Usage:   ./supor-user-deploy.sh key_file option"
	echo "         option:  yes, Enable Root Login"
	echo "                  no, Disable Root Login"
	echo "Example: ./supor-user-deploy.sh supor-user_rsa.pub yes"
	exit
elif ! [[ $2 = "yes"||$2 = "no" ]]; then
	echo "The second argument is wrong! Must enter 'yes' or 'no'"
	exit
fi

useradd supor-user
mkdir ~supor-user/.ssh
echo "[`date +"%Y-%m-%d %H:%M:%S"`] 'supor-user' created."
sleep 1

read pub_key < $1
echo $pub_key >> ~supor-user/.ssh/authorized_keys
echo "[`date +"%Y-%m-%d %H:%M:%S"`] 'supor-user' public key imported."
echo "---------------------------------------------------------------"
char_per_line=60;
for ((i=0; i<${#pub_key}; i++)); 
do 
	arr_pub_key[i]=${pub_key:i:1}
	echo -n "${arr_pub_key[i]}"
	if [ $(( (i+1)%char_per_line )) = 0 ]; then echo " ";
	fi
done
echo " "
echo "---------------------------------------------------------------"
sleep 1

chown supor-user:supor-user ~supor-user/.ssh
chmod 0755 ~supor-user/.ssh/
chmod 0644 ~supor-user/.ssh/authorized_keys
echo "[`date +"%Y-%m-%d %H:%M:%S"`] public-key file permission modified."
sleep 1

echo "supor-user ALL=(ALL) NOPASSWD: ALL" > /etc/sudoers.d/supor-user
echo "[`date +"%Y-%m-%d %H:%M:%S"`] 'supor-user' NOPASSWD privilege added."
sleep 1

if [[ $2 = "yes" ]]; then
	sed -i -e "s/#UseDNS yes/UseDNS no/g" \
		   -e "s/#PermitEmptyPasswords no/PermitEmptyPasswords no/g" \
		   /etc/ssh/sshd_config
elif [[ $2 = "no" ]]; then
	sed -i -e "s/#UseDNS yes/UseDNS no/g" \
		   -e "s/#PermitEmptyPasswords no/PermitEmptyPasswords no/g" \
		   -e "s/#PermitRootLogin yes/PermitRootLogin no/g" \
		   -e "s/PermitRootLogin yes/PermitRootLogin no/g" \
		   /etc/ssh/sshd_config
fi
sleep 1

systemctl restart sshd
echo "[`date +"%Y-%m-%d %H:%M:%S"`] sshd service restart."